/* eslint-disable jsx-a11y/anchor-is-valid */
import { InfiniteScroll, Input, Modal, Toast } from 'antd-mobile'
import './index.less'
import { useEffect, useState } from 'react'
import { WbShop, BatchBuy, WbList, OpenGiff, NoticeList, RecordList } from '../../../api/active'
import { GetUserInfo } from '../../../api/mine'
import appSdk from '../../../utils/app_sdk'

function arraymove(arr, fromIndex, toIndex) {
  var element = arr[fromIndex]
  arr.splice(fromIndex, 1)
  arr.splice(toIndex, 0, element)
  return arr
}
const gameTitle = '粽游天下'

// 积分抽奖 萌岛挖宝
export default function CoinLottery() {
  const [buyNum, setBuyNum] = useState(1) // 装扮数量
  const [buyNum2, setBuyNum2] = useState(1) // 装扮数量
  const [saleItem, setSaleItem] = useState([]) // 购买商品列表
  // const [selectBuy, setSelectBuy] = useState(saleItem[0]);

  const [nums, setNums] = useState([1, 10, 100])
  const [selectNum, setSelectNum] = useState(1) // 铲子数量

  const [chanZiList, setChanZiList] = useState([]) // 铲子列表
  const [selectChanZi, setSelectChanZi] = useState({ box_show_data: [] })

  const [ruleVisible, setRuleVisible] = useState(false)
  const [userInfo, setUserInfo] = useState({ mizuan: 0, mibi: 0 })

  const [resultVisible, setResultVisible] = useState(false)
  const [resultData, setResultData] = useState([])

  const [noticeData, setNoticeData] = useState([])
  const [recordList, setRecordList] = useState([])
  const [recordVisible, setRecordVisible] = useState(false)

  const getUserInfo = () => {
    GetUserInfo().then((res) => {
      setUserInfo(res.data || [])
    })
  }

  useEffect(() => {
    document.title = gameTitle
    Toast.show({ icon: 'loading', content: '加载中...', maskClickable: false })
    WbShop().then((res) => {
      setSaleItem(res.data)
      // setSelectBuy(res.data[0]);
      // 偷懒了
      if (res.data) {
        setBuyNum(1)
        setBuyNum2(1)
      }
    })
    WbList({
      type: '3'
    }).then((res) => {
      setChanZiList(res?.data.list)
      setNums(res.data.nums)
      // const CenterIndex = res?.data.list[0].findIndex(item => item.is_zj)
      // const arr = arraymove(res?.data.list[0].box_show_data, CenterIndex, 4) // 放到中间
      setSelectChanZi(res?.data.list[0]) // 默认设置第一个列表礼物
    })
    NoticeList({
      type: '3'
    })
      .then((res) => {
        setNoticeData(res?.data || [])
      })
      .catch((err) => {
        Toast.show({ content: err.message, maskClickable: false, position: 'bottom' })
      })
    getUserInfo()
  }, [])

  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const getRecordList = async () => {
    try {
      const res = await RecordList({ page, type: '3' })
      if (res.data && res.data?.length) {
        setRecordList(page === 1 ? res.data : recordList.concat(res.data))
      }
      if (res.data && res.data?.length >= 10) {
        setPage(page + 1)
        setHasMore(true)
      } else {
        setHasMore(false)
      }
    } catch {
      setHasMore(false)
    }
  }

  useEffect(() => {
    if (!resultVisible) {
      setPage(1)
      setHasMore(true)
      setRecordList([])
    }
  }, [resultVisible])

  const openGift = () => {
    Toast.show({
      icon: 'loading',
      maskClickable: false,
      content: '加载中...'
    })
    OpenGiff({
      box_id: selectChanZi.id,
      nums: selectNum
    })
      .then((res) => {
        // console.log(res);
        if (res.data && res.data.length) {
          setResultData(res.data)
          setResultVisible(true)
        }
        getUserInfo()
        Toast.clear()
      })
      .catch((err) => {
        Toast.show({
          content: err.message || '系统错误',
          maskClickable: false
        })
      })
  }

  // 买积分
  const BatchBuyCoin = (item, idx) => {
    if (+userInfo.mizuan >= item.price * buyNum) {
      Toast.show({
        icon: 'loading',
        maskClickable: false,
        content: '加载中...'
      })
      BatchBuy({
        nums: !idx ? buyNum : buyNum2,
        goods_id: item?.id
      })
        .then((res) => {
          console.log(res)
          getUserInfo()
          if (res.data) {
            Toast.show({
              content: res.message,
              icon: 'success',
              maskClickable: false
            })
          } else {
            Toast.show({
              content: res.message,
              maskClickable: false
            })
          }
        })
        .catch((err) => {
          Toast.show({
            content: err?.message || '系统错误',
            maskClickable: false
          })
        })
    } else {
      Toast.clear()
      // 余额不足
      Toast.show({
        content: '余额不足',
        maskClickable: false
      })
      appSdk('jumpToRecharge')
      // appSdk('closeWebview')
    }
  }

  // 格式积分
  // const getPoint = (num) => {
  //   if (num < 1000) return num;
  //   if (1000 <= num && 10000 > num) return Number(parseFloat(num / 1000).toFixed(2).slice(0, -1)) + 'k'
  //   if (10000 <= num && 100000000 > num) return Number(parseFloat(num / 10000).toFixed(2).slice(0, -1)) + 'w'
  // }

  const scrollToTop = () => {
    let sTop = document.documentElement.scrollTop || document.body.scrollTop
    if (sTop > 0) {
      window.requestAnimationFrame(scrollToTop)
      window.scrollTo(0, sTop - sTop / 8)
    }
  }

  const [gifData, setGifData] = useState([])
  useEffect(() => {
    setGifData(arraymove(selectChanZi?.box_show_data || [], 0, 5))
    console.log(arraymove(selectChanZi?.box_show_data || [], 0, 5))
  }, [selectChanZi])

  return (
    <div className="coin_lottery_wrap2">
      <div className="zhuangban_wrap">
        {/* <div className="close_btn" onClick={() => appSdk('closeWebview')}></div> */}
        <div className="title" id="get_coin" />
        <div className="sale_items">
          {saleItem.map((item, idx) => (
            <div className="sale_box">
              <div className="sale_item">
                <div className="img">
                  <img src={item?.show_img} alt="" />
                </div>
                {item?.give_point ? <div className="point">+{item?.give_point}积分</div> : null}
              </div>
              <div className="sale_info">
                <div className="name ellipsis1">
                  {item?.type === 4 ? '头像框' : '进场特效'}：{item.name}
                </div>
                <div className="price">
                  <span>{item.price}</span>
                  <span>{window.baseConfig.coin_name}/天</span>
                </div>
              </div>
              <div className="sale_action">
                <div
                  className="down act"
                  onClick={() => {
                    !idx ? setBuyNum(buyNum > 1 ? +buyNum - 1 : 1) : setBuyNum2(buyNum2 > 1 ? +buyNum2 - 1 : 1)
                  }}
                ></div>
                <div className="nums">
                  <Input
                    onChange={(v) => {
                      if (+v > 100) {
                        !idx ? setBuyNum(100) : setBuyNum2(100)
                      } else {
                        !idx ? setBuyNum(Number(v).toFixed(0).replace(/^0+/, '')) : setBuyNum2(Number(v).toFixed(0).replace(/^0+/, ''))
                      }
                    }}
                    type="number"
                    value={!idx ? buyNum : buyNum2}
                    min={1}
                    max={100}
                  />
                </div>
                <div
                  className="add act"
                  onClick={() => {
                    !idx ? setBuyNum(buyNum < 100 ? +buyNum + 1 : 100) : setBuyNum2(buyNum2 < 100 ? +buyNum2 + 1 : 100)
                  }}
                ></div>
              </div>
              <p>单位：个</p>
              <div className="buy_btn" onClick={() => BatchBuyCoin(item, idx)}>
                立即购买
              </div>
            </div>
          ))}
        </div>
        <div className="sale_tips">
          <p>
            <span>积分说明：</span>
            限时活动商品为绝版限定精美商品，活动期后无法购买。限时活动时间:
          </p>
          <p>
            <span>限时活动惊喜：</span>
            购买商品赠送对应积分，积分可用于参与穿越时光机限时活动及其它活动。积分为赠送品，本身无价值，不支持平台流通:
          </p>
        </div>
      </div>
      <div className="wabao">
        <div className="title" />
        <div className="menu_list">
          {chanZiList.map((item) => (
            <div className={`item ${item.id === selectChanZi.id ? 'active' : ''}`} onClick={() => setSelectChanZi(item)}>
              <img src={item.id === selectChanZi.id ? item.img : item.hyaline_img} alt="" />
            </div>
          ))}
        </div>
        <div className="gonggao_tips">
          <div className="record_btn" onClick={() => setRecordVisible(true)}>
            粽包记录
          </div>
          <div className="gonggao ">
            <div className="con">
              {noticeData?.map((item) => (
                <p className="txt ellipsis1">
                  恭喜<span className="name">{item?.nickname.slice(0, 3) + '**'}</span>使用
                  <span className="box">{item?.box_name}</span>获得
                  <span className="award">{item?.award}</span>
                </p>
              ))}
            </div>
          </div>
          <div className="rule_btn" onClick={() => setRuleVisible(true)}>
            粽包规则
          </div>
        </div>
        <div className="gift_data">
          {gifData.slice(0, 9).map((item, idx) => (
            <div className="around_item">
              <img src={item?.show_img} alt="" />
            </div>
          ))}
          {/* <div className="around_item"></div>
          <div className="around_item"></div>
          <div className="around_item"></div>
          <div className="around_item"></div>
          <div className="around_item"></div>
          <div className="around_item"></div>
          <div className="around_item"></div>
          <div className="around_item"></div> */}
          {/* {selectChanZi?.box_show_data
            .filter((i) => i.is_zj)
            .map((item) => (
              <div className="center_item">
                <img src={item.show_img} alt="" />
              </div>
            ))}
          {selectChanZi?.box_show_data
            .filter((i) => !i.is_zj)
            .slice(0, 8) // 限制8个
            .map((item, idx) => (
              <div className={`around_item a_${idx + 1}`} key={idx}>
                <img src={item.show_img} alt="" />
              </div>
            ))} */}
        </div>
        <div className="user_data">
          <p>
            剩余积分:{+userInfo?.points || 0}{' '}
            <span onClick={scrollToTop} style={{ textDecoration: 'underline' }}>
              获取积分
            </span>{' '}
          </p>
          {/* <div className="get_coin btn"><a href="#" onClick={scrollToTop}>获取积分</a></div>
          <div className="coin_num btn">剩余{getPoint(+userInfo?.points || 0)}积分</div> */}
        </div>
        <div className="get_gift_wrap">
          <div className="wabao_btn" onClick={openGift}>
            <span>立即打开</span>
          </div>
          {nums.map((i) => (
            <div onClick={() => setSelectNum(i)} className={`num_btn ${selectNum === i ? 'active' : ''}`} key={i}>
              <span>x{i}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="active_tips">本活动最终解释权归{window.baseConfig.package_name}所有。</div>

      <Modal
        closeOnMaskClick={true}
        onClose={() => setRuleVisible(false)}
        visible={ruleVisible}
        content={
          <div className="mo_contetn">
            <div className="scorll">
              <RuleDetail url={selectChanZi?.rule_img} chanZiList={chanZiList} />
            </div>
          </div>
        }
      />

      <Modal
        closeOnMaskClick={true}
        onClose={() => setResultVisible(false)}
        visible={resultVisible}
        content={
          <div className="result_box">
            <div className="tit">恭喜获得</div>
            <div className="scorll">
              {resultData?.map((item) => (
                <div className="data_item">
                  <img src={item.img} alt="" />
                  <div className="info">
                    <p className="name ellipsis1">{item.name}</p>
                    <span>x{item?.nums || 1}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        }
      />

      <Modal
        closeOnMaskClick={true}
        onClose={() => setRecordVisible(false)}
        visible={recordVisible}
        destroyOnClose
        content={
          <div>
            <RecordDetail recordList={recordList} getRecordList={getRecordList} hasMore={hasMore} />
          </div>
        }
      />
    </div>
  )
}

export function RuleDetail({ url, chanZiList }) {
  return (
    <div className="rule">
      <div>
        <p className="rule_tit">粽包规则</p>
        <p>
          1.参与"{gameTitle}"游戏分别最低需
          {chanZiList.map((item) => (
            <span>
              ，消耗积分{item.point}即可打开“{item.name}”
            </span>
          ))}
        </p>
        <p>2.打开棕包后，即可直接获得相应的奖品，抽的的奖品可在"奖品详情"查看；</p>
        <p>
          3."{gameTitle}"旨在提升聊天室娱乐的互动性，本互动功能中所获得道具均不可进行撤销、退款或退换，不可兑换成
          {window.baseConfig.coin_name}、现金、不可再次交易；您承诺不使用本功能进行任何违反法律法规及本平台规则、规范的活动或行为；
        </p>
        <p>4.本活动最终解释权归{window.baseConfig.package_name}所有。</p>
      </div>
      <div>
        <p className="rule_tit">奖品详情</p>
        <div>
          <img src={url} alt="" />
        </div>
      </div>
    </div>
  )
}

export function RecordDetail({ recordList = [], getRecordList, hasMore }) {
  const [moreNote, setMoreNote] = useState('')
  return (
    <div className="record">
      <div className="tit">粽包记录</div>
      <div className="list">
        {recordList.map((item) => (
          <div className="item_data" key={item.create_time}>
            <div
              className="item"
              onClick={() => {
                if (item.create_time === moreNote) {
                  setMoreNote(null)
                } else {
                  setMoreNote(item.create_time)
                }
              }}
            >
              <div className="info">
                <div className="name">
                  {item.box_name}x{item.nums}
                </div>
                <div className="time">{new Date(parseInt(item.create_time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')}</div>
              </div>
              <div className="note ellipsis1">{item.note}</div>
            </div>
            {moreNote === item.create_time ? <div className="more_note">{item.note}</div> : null}
          </div>
        ))}
        <InfiniteScroll loadMore={getRecordList} threshold={150} hasMore={hasMore} />
      </div>
    </div>
  )
}
